//
//  Logs.swift
//  JXBaseTools
//
//  Created by godox on 2021/11/30.
//

import Foundation

/// 全局的DEBUG模式下的打印
/// - Parameters:
///   - message: 需要打印的消息
///   - file: 打印所在的文件
///   - line: 打印所在的函数的行数 可以使用 command + shift o 快速跳转到文件再使用 command+L跳转到对应的行数
public func JXLog(_ message: Any...,
                     file:String = #file,
                     line:Int = #line) {
    #if DEBUG
    let fileName = (file as NSString).lastPathComponent
    let threadWarning = Thread.isMainThread ? "" : " | ⚠️Warning: NOT-MAIN-THREAD"
    let topP = "--------------------------------🌺🌺🌺--------------------------------"
    print(topP)
    let infoP = "🌿Time：\(Date.onlyTime) 🌺FileName：\(fileName), 🍀Line：\(line)\(threadWarning)"
    print(infoP)
    var messageP: String = ""
    for (idx, item) in message.enumerated() {
        print("\(idx) ➜ \(item)")
        messageP.append("\(idx) ➜ \(item)")
    }
    let lastP = "--------------------------------🍀🍀🍀--------------------------------"
    print(lastP)
    DispatchQueue.global().async {
        LogFileManager(logType: .log).write(log: topP + "\n" + infoP + "\n" + messageP + "\n" + lastP)
    }
    #endif
}

public enum LogType {
    
    case meshJson
    case log
    
    var txt: String {
        switch self {
        case .meshJson:
            return "meshJson.txt"
        case .log:
            return "log.txt"
        }
    }
    
}


public class LogFileManager {
    
    private var logFileHandle: FileHandle?
    private var logType: LogType = .log
    public init(logType: LogType) {
        self.logType = logType
        if let logFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(logType.txt) {
            if !FileManager.default.fileExists(atPath: logFilePath.path) {
                FileManager.default.createFile(atPath: logFilePath.path, contents: nil, attributes: nil)
            }
            
            do {
                logFileHandle = try FileHandle(forWritingTo: logFilePath)
            } catch {
                print(error.localizedDescription)
            }
        }
    }

    deinit {
        logFileHandle?.closeFile()
    }

    public func write(log text: String) {
        guard let data = "\(text)\n".data(using: .utf8) else { return }
        
        logFileHandle?.seekToEndOfFile()
        logFileHandle?.write(data)
    }
    
    @discardableResult
    public func delete() -> Bool {
        
        if let logFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(logType.txt) {
            do {
                try FileManager.default.removeItem(at: logFilePath)
                print("Deleted \(logType.txt)")
                return true
            } catch {
                print(error.localizedDescription)
                return false
            }
        } else {
            return false
        }
    }
}
